/*
* method:
*       minidate:  $("selector").cdatePicker("minidate","2001-1-3");
*       maxdate:
* */
(function($){
    var EV_CALL_METHOD="EV_CALL_METHOD";
    var EV_VALUE_CONFIRM="confirm";                 //隐藏时
    var eventCenter =  $("<a></a>");
    var defaultOptions={
        zTop:5000,
        zBottom:-10,
        yOffset:10,
        inFancybox:false,
        onSelect:function(){},
        selectIconSrc:false,                     //指向某icon
        yearItarval:5,
        formatInInput:"{year}-{month}-{day}",
        noReadOnly:false,
        autoAddSelectOptionMount:10             //年份前进后退时候，到达边沿自动增加年份选项，每次增加的量
    };
    $.fn.cdatePicker=function(options,param){


        this.each(function(){
            var ti=$(this),data=ti.data();
            if(typeof(options) == "string"){
                ti.trigger(EV_CALL_METHOD,{method:options,para:param});
                //return this;
            }

            var opts = data.opts = data.opts || {};
            $.extend(true,opts,defaultOptions);
            $.isPlainObject(options) && $.extend(true,opts,options);

            //初始化
            if(!data.cdataPicker){
                data.cdataPicker=true;
                var dContainer= data.dContainer = $("<div></div>",{"jqPlug":"cdatePicker"});
                var icon;
                if(opts.selectIconSrc){
                    icon = $("<img/>",{src:opts.selectIconSrc});
                    icon.css({borderWidth:"0px",marginBottom:"-3px",cursor:"pointer",marginLeft:5});
                    ti.after(icon);
                    icon = data.icon = ti.next();
                    icon.bind("click",function(){show.call(ti);});
                }else{
                    ti.bind("focus",function(){show.call(ti);});
                }

                if(!opts.noReadOnly){
                    ti.attr("readonly",true);
                    if(!opts.selectIconSrc)
                        ti.css({cursor:"pointer"});
                }
                var datepickerOptions= data.datepickerOptions={
                    onSelect:function(dateString){
                        opts.onSelect();
                        //alert(dContainer.datepicker("getDate"));
                        ti.val(dateString);
                        ti.attr("value",dateString);
                        hide.call(ti);
                    },
                    onChangeMonthYear:function(year,month,obj){}
                };
                dContainer.datepicker(datepickerOptions);
                //增加年份和月份选择
                var monthYearTarContainerSelector = ".ui-datepicker-title";
                //月份
                var monthSel = data.monthSel = $("<select></select>",{id:"monthSel"}).css({width:65,margin:"0 20px 0 0px"});
                var monthNames = $.datepicker.regional['zh-CN'].monthNames;
                //年份
                var yearSel = data.yearSel = $("<select></select>",{id:"yearSel"}).css({margin:"0 4px",width:70});
                //左右选择年份功能
                var leftyear = $("<a class='ui-icon ui-icon-circle-triangle-w'></a>");
                var rightyear = $("<a class='ui-icon ui-icon-circle-triangle-e'></a>");
                var cssSeting = {display:"inline-block",cursor:"pointer",verticalAlign:"middle"};
                leftyear.css(cssSeting);
                rightyear.css(cssSeting);

                if(ti.attr("minDate")) setMinDate(parseDate(ti.attr("minDate")) || new Date());
                if(ti.attr("maxDate")) setMaxDate(parseDate(ti.attr("maxDate")) || new Date());
                if(!ti.attr("minDate") &&!ti.attr("maxDate"))freshMaxMinDate();

                setData.call(ti,parseDate(ti.val()) || parseDate(ti.attr("cdate")) || new Date());                  //读取默认设置

                var jquiDatapickerDiv = data.jquiDatapickerDiv = dContainer.children("div").first();
                dContainer
                    .css({
                        position:"absolute",
                        width:jquiDatapickerDiv.width(),
                        height:jquiDatapickerDiv.height()
                    })
                    .appendTo($("body"))
                ;
                hide.call(ti,true);
                $(document).bind("click",function(e){
                    var tar = e.target;
                    if(
                        ti[0]!=tar &&
                        (!data.icon || (data.icon && data.icon[0]!=tar)) &&
                        data.dContainer[0]!=tar&&
                        !$.contains(data.dContainer.children("div")[0],tar)
                    ){
                        hide.call(ti);
                    }
                });



                $(window).resize(function(){
                    data.visible && (!data.icon) && show.call(ti);
                });
                data.method={
                    rePutSelect:rePutSelect
                };

                //方法调用
                var methodMap ={};
                ti.bind(EV_CALL_METHOD,function(e,methodObject){
                    var med = methodMap[methodObject.method];
                    med && med.call(this,methodObject.para);
                });

                methodMap.mindate=function(para){
                    var date;
                    if(typeof(para) == "string"){
                        date=parseDate(para)
                    }else{
                        date=para;
                    }
                    setMinDate(date);
                }

                methodMap.maxdate=function(para){
                    var date;
                    if(typeof(para) == "string"){
                        date=parseDate(para)
                    }else{
                        date=para;
                    }
                    setMaxDate(date);
                }

                //---以下为定义部分---
                //刷新年份显示
                function freshYearSel(adate){
                    adate = adate||dContainer.datepicker( "getDate");
                    yearSel.empty();
                    for(var i=data.dataCache.yearMin;i<=data.dataCache.yearMax;i++){
                        var optionString = "<option value='{value}'>{name}</option>";
                        optionString = optionString.replace("{value}",i).replace("{name}",i+"年");
                        $(optionString).appendTo(yearSel);
                    }
                    yearSel.val(adate.getFullYear());
                }
                function freshMonthSel(adate,isMinyear,isMaxyear){
                    adate = adate||dContainer.datepicker( "getDate");
                    var monthStart,monthEnd;
                    monthStart = 0;monthEnd=11;
                    if(isMinyear && data.datepickerOptions.minDate) monthStart=data.dataCache.monthMin;
                    if(isMaxyear && data.datepickerOptions.maxDate) monthEnd=data.dataCache.monthMax;

                    monthSel.empty();
                    for(var i=monthStart;i<monthEnd+1;i++){
                        var key= i,item=monthNames[i];
                        var optionString = "<option value='{value}'>{name}</option>";
                        optionString = optionString.replace("{value}",key).replace("{name}",item);
                        $(optionString).appendTo(monthSel);
                    }
                    monthSel.val(adate.getMonth());
                }

                function monthSelChange(e){
                    setData.call(ti,{month:monthSel.val()});
                    rePutSelect();
                }

                function yearSelChange(e){
                    if(e){              //浏览器触发才会设置
                        setData.call(ti,{year:yearSel.val()});
                        rePutSelect();
                    }
                    var adate = dContainer.datepicker( "getDate");//data.currentDate;
                    yearSel.val(adate.getFullYear());
                    freshMonthSel(
                        adate,
                        adate.getFullYear()==data.dataCache.yearMin,
                        adate.getFullYear()==data.dataCache.yearMax
                    );
                }

                function getDatapickerInnerObject(selector){
                    return dContainer.find(monthYearTarContainerSelector);
                }

                function rePutSelect(){
                    var container = getDatapickerInnerObject(monthYearTarContainerSelector);
                    monthSel.bind("change",monthSelChange).appendTo(container);
                    leftyear.appendTo(container).bind("click",{dir:-1},yearButtonClick);;
                    yearSel.bind("change",yearSelChange).appendTo(container);
                    rightyear.appendTo(container).bind("click",{dir:1},yearButtonClick);;
                    container.find(".ui-datepicker-month,.ui-datepicker-year").css({display:"none"});
                    dContainer.find(".ui-datepicker-prev,.ui-datepicker-next").css({display:"none"});
                    container.css({margin:"0"});
                }

                function yearButtonClick(e){
                    var yearTarValue = yearSel.val()*1 + e.data.dir;
                    var option = yearSel.children("option[value="+ yearTarValue +"]");
                    var isback = e.data.dir<0;

                    if(data.datepickerOptions.minDate &&  isback && yearTarValue<data.dataCache.yearMin){
                        return;
                    }
                    if(data.datepickerOptions.maxDate && !isback && yearTarValue>data.dataCache.yearMax){
                        return;
                    }
                    if(option.length == 0){
                        var startValue = isback?yearTarValue-opts.autoAddSelectOptionMount:yearTarValue
                        var endValue = isback?yearTarValue:yearTarValue+opts.autoAddSelectOptionMount
                        addOptionInSelect(isback,startValue,endValue);
                    }
                    yearSel.val(yearTarValue);
                    yearSel.trigger("change");

                    function addOptionInSelect(isFront,startValue,endValue){
                        var optionString = "<option value='{value}'>{name}</option>";
                        var i;
                        if(isFront){
                            for(i=endValue;i>=startValue;i--){yearSel.prepend(getOption(i))}
                        }else{
                            for(i=startValue;i<=endValue;i++){yearSel.append(getOption(i))}
                        }
                        function getOption(index){
                            return $(optionString.replace("{value}",index).replace("{name}",index+"年"))
                        }
                    }
                }

                function setMaxDate(dt){
                    var dtopt={maxDate:dt};
                    $.extend(data.datepickerOptions,dtopt);
                    dContainer.datepicker("option",dtopt);
                    freshMaxMinDate();
                }

                function setMinDate(dt){
                    var dtopt={minDate:dt};
                    $.extend(data.datepickerOptions,dtopt);
                    dContainer.datepicker("option",dtopt);
                    freshMaxMinDate();
                }

                function freshMaxMinDate(){
                    //选择框中最大最小年月
                    var curDate =  dContainer.datepicker("getDate");
                    var yearminValue,yearmaxValue;
                    yearminValue = curDate.getFullYear()-opts.yearItarval*1;
                    yearmaxValue = curDate.getFullYear()+opts.yearItarval*1;
                    if(datepickerOptions.minDate){
                        yearminValue = Math.max(yearminValue,datepickerOptions.minDate.getFullYear())
                    }
                    if(datepickerOptions.maxDate){
                        yearmaxValue = Math.min(yearmaxValue,datepickerOptions.maxDate.getFullYear())
                    }

                    data.dataCache={
                        yearMax:yearmaxValue,
                        yearMin:yearminValue,
                        monthMax:datepickerOptions.maxDate?datepickerOptions.maxDate.getMonth():undefined,
                        monthMin:datepickerOptions.minDate?datepickerOptions.minDate.getMonth():undefined
                    };

                    freshYearSel();
                    yearSelChange(null);
                    rePutSelect();
                }
            }//初始化结束
        });

        //隐藏
        function hide(isForce){
            var data=this.data();
            if(!data.visible && !isForce) return;
            data.dContainer.css({
                visibility:"hidden",
                zIndex:data.opts.zBottom
            });
            data.visible=false;
            if(data.lastConfirmData && data.dContainer.datepicker("getDate").getTime()!=data.lastConfirmData.getTime()){
                this.trigger(EV_VALUE_CONFIRM);
            }
            data.lastConfirmData=data.dContainer.datepicker("getDate");
        }

        //显示
        function show(){
            var data=this.data();
            var offsetObject = data.icon?{left:mousex,top:mousey-this.height()}:this.offset();
            var tarTop=offsetObject.top,tarLeft=offsetObject.left;
            data.dContainer.css({
                visibility:"",
                zIndex:data.opts.zTop,
                top:tarTop+data.opts.yOffset+this.height(),
                left:tarLeft
            });
            data.visible=true;
            if(data.method.rePutSelect) data.method.rePutSelect();
        }

        //设置控件的值
        function setData(date_str){
            var dateObject = null,data=this.data();;
            if(!date_str){
                dateObject=new Date;
            }else if(typeof(date_str)=="string"){           //只接受'yy-mm-dd'格式
                dateObject = parseDate(date_str);
            }else if(typeof(date_str)=="object" && !$.isPlainObject(date_str)){
                dateObject=date_str;
            }else if($.isPlainObject(date_str)){
                dateObject=data.dContainer.datepicker( "getDate");//new Date();
                date_str.year && dateObject.setFullYear(date_str.year);
                date_str.month!=undefined && dateObject.setMonth(date_str.month);
                date_str.day!=undefined && dateObject.setDate(date_str.day);
            }
            data.dContainer.datepicker( "setDate",dateObject);
            var dt = data.currentDate = data.dContainer.datepicker( "getDate");
            var result = {year:dt.getFullYear(),month:dt.getMonth()+1,day:dt.getDate()};
            var formatString = data.opts.formatInInput;
            this.val(formatString.replace("{year}",result.year).replace("{month}",result.month).replace("{day}",result.day));
        }
        return this;
    }

    var mousex=0,mousey=0;
    $(document).bind("mousemove",function(e){
        mousex= e.clientX; mousey= e.clientY;
    });


    //汉化jqui日历
    $.datepicker.regional['zh-CN'] = {
        clearText: '清除',
        clearStatus: '清除已选日期',
        closeText: '关闭',
        closeStatus: '不改变当前选择',
        prevText: '<上月',
        prevStatus: '显示上月',
        prevBigText: '<<',
        prevBigStatus: '显示上一年',
        nextText: '下月>',
        nextStatus: '显示下月',
        nextBigText: '>>',
        nextBigStatus: '显示下一年',
        currentText: '今天',
        currentStatus: '显示本月',
        monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
        monthNamesShort: ['一','二','三','四','五','六', '七','八','九','十','十一','十二'],
        monthStatus: '选择月份',
        yearStatus: '选择年份',
        weekHeader: '周',
        weekStatus: '年内周次',
        dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
        dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        dayStatus: '设置 DD 为一周起始',
        dateStatus: '选择 m月 d日, DD',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        initStatus: '请选择日期',
        isRTL: false};
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);

    function parseDate(str){
        if(typeof str == 'string'){
            var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
            if(results && results.length>3)
                return new Date(results[1],results[2] -1,results[3]);
            results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
            if(results && results.length>6)
                return new Date(results[1],results[2] -1,results[3],results[4],results[5],results[6]);
            results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);
            if(results && results.length>7)
                return new Date(results[1],results[2] -1,results[3],results[4],results[5],results[6],results[7]);
        }
        return null;
    }
})(jQuery)